package top;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author chenyw
 * @date 2022/7/10 22:31
 * @description     填充每个节点的下一个右侧指针节点
 */
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
public class Top116connect {
/*    public Node connect(Node root) {
        if (root == null) {
            return root;
        }
        //层序遍历 o(n)空间复杂度
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int n = queue.size();
            Node p = new Node();
            for (int i = 0; i < n; i++) {
                Node node = queue.poll();
                p.next = node;
                p = node;
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return root;
    }*/

    //常量级空间复杂度
    public Node connect(Node root) {
        if (root == null) {
            return root;
        }
        Node firstLeft = root;
        Node p;
        while (firstLeft.left != null) {
            p = firstLeft;
            while (p != null) {
                p.left.next = p.right;
                if (p.next != null) {
                    p.right.next = p.next.left;
                }
                p = p.next;
            }
            firstLeft = firstLeft.left;
        }
        return root;
    }

}
